import React, { useState, useRef, useEffect } from 'react'
import { useNavigate, useParams, useLocation } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import { NavBar, Space, Toast } from 'antd-mobile'
import "../css/OmiS.css"
import { CloseOutline, MoreOutline, SearchOutline } from 'antd-mobile-icons'
import io from 'socket.io-client'
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:3000/"
export default function OmiSinfo() {
    const messagesRef = useRef(null);
    const isAtBottomRef = useRef(true);
    const location = useLocation()
    let navpush = useNavigate()
    const back = () => {
        navpush(-1)
    }
    //挑进来携带房间的_id
    //根据房间的_id来获取数据
    //房间名
    let [rname, setrname] = useState('')
    //聊天室的id
    let rid = useParams().id
    
    //获取房间数据
    let [roominfo, setroominfo] = useState(null)
    let getinfo = async () => {
        let res = await axios.get(`sinroom?id=${rid}`)
        if (res.data.code == 200) {
            setroominfo(res.data.info)

        }
    }

    //当前用户的id
    let uid = JSON.parse(sessionStorage.getItem("user"))._id
    let [uidinfo,setuidinfo] = useState(null)
    //被连接用户id
    let eid = useParams().id1
    let [eidinfo,seteidinfo] = useState(null)
    //获取当前用户信息
    let getuserinfo = async() => {
        let res = await axios.get(`usermsg?id=${uid}`)
        if (res.data.code == 200) {
            setuidinfo(res.data.info)
        }
    }
    let getuserinfo1 = async() => {
        let res = await axios.get(`usermsg?id=${eid}`)
        if (res.data.code == 200) {
            seteidinfo(res.data.info)
        }
    }
    useEffect(() => {
        getuserinfo()
        getuserinfo1()
    }, [])
    //输入框信息
    let [msg, setmsg] = useState('')
    //socket对象
    const [socket, setSocket] = useState(null);
    //聊天记录
    let [payloves, setpayloves] = useState([])
    useEffect(() => {
        getinfo()

    }, [])
    useEffect(() => {
        //链接socket.io服务器
        const newSocket = io('http://127.0.0.1:3001', {
            reconnection: true,
            reconnectionAttempts:5,
            reconnectionDelay: 1000,
            query: {
                uid,
                eid
            }
        })
        setSocket(newSocket)
        newSocket.on('reconnect', () => {
            newSocket.emit('joinRoom', rname, { _id: uid, el_id: eid, rid })
          });
       
          newSocket.on('reconnect_error', (error) => {
            console.error('重连失败', error);
          });
        //获取服务器返回的房间名
        newSocket.on('welcome', (message) => {

            setrname(message)
        });
        //向服务器发送链接聊天室请求
        newSocket.emit('joinRoom', rname, { _id: uid, el_id: eid, rid })
        //客户端接受服务器返回的聊天信息
        newSocket.on('roomMessageReceived', (message) => {
            setpayloves(message[0].messages)
            
        });
    }, [rname])
    useEffect(() => {
        if (messagesRef.current) {
          const shouldScrollToBottom =
            messagesRef.current.scrollTop + messagesRef.current.clientHeight ===
            messagesRef.current.scrollHeight;
          if (shouldScrollToBottom) {
            messagesRef.current.scrollTop = messagesRef.current.scrollHeight;
          }
        }
      }, [payloves]);
    return (
        <div>
            <NavBar onBack={back} style={{ width: '100%', backgroundColor: "rgb(255,255,255)", fontSize: '2rem', fontWeight: '900', position: "fixed", top: '0', left: '0' }}>{roominfo && roominfo.roomname.split(",").filter(item => item != JSON.parse(sessionStorage.getItem("user")).username)}</NavBar>
            <div className="content_omis" ref={messagesRef}>
                {payloves.map(item => {
                    // return <p key={item._id} style={item.sender === uid?{textAlign:'right'}:{textAlign: 'left'}}>{item.sender === uid?`${item.content}:${item.sender}`:`${item.sender}:${item.content}`}</p>
                    return <div className={item.sender === uid ? "infoctnr" : "infoctn"} key={item._id}>
                        {item.sender === uid ?
                            <><div className="userinfo">
                                {item.content}
                            </div><div className="userhd">
                            <img
        src={uidinfo.avatar}
        alt="description"
        style={{
          width: '100%',
          height: '100%',
          objectFit: 'cover',
          borderRadius: '50%'
        }}
      />
                    </div></> : <><div className="userhd">
                    <img
        src={eidinfo.avatar}
        alt="description"
        style={{
          width: '100%',
          height: '100%',
          objectFit: 'cover',
          borderRadius: '50%'
        }}
      />
                    </div>
                                <div className="userinfo">
                                    {item.content}
                                </div></>}
                    </div>
                })}
            </div>
            <div id="btminp">
                <div className="inpbox">
                    <input type="text" value={msg} onChange={(e) => {
                        setmsg(e.target.value)
                    }} />
                    {msg === '' && <div className="bf">+</div>}
                    {msg !== "" && <button onClick={() => {
                        socket.emit('roomMessage', msg, rname, { sender: uid, roomid: rid })
                        setmsg('')
                    }}>发送</button>}
                </div>
            </div>
        </div>
    )
}
